package com.nsgf.library.ui.page;

import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.DiffUtil;

import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.model.GradientColor;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.bean.HomeDeviceOpeningBean;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.bean.WaterDetailInfoBean;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.databinding.ActivityRainChartBinding;
import com.nsgf.library.databinding.ItemRainTimeDetailBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.ui.adapter.SimpleDataBindingPositionAdapter;
import com.nsgf.library.ui.adapter.ViewHolder;
import com.nsgf.library.widget.MyMarkerView;
import com.nsgf.library.widget.prckerview.TimePickerView;
import com.nsgf.skjz.utils.Kits;
import com.nsgf.skjz.utils.UnitTo;
import com.nsgf.skjz.utils.Utils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 雨情
 */
public class RainDetailActivity extends BaseActivity implements
        OnChartValueSelectedListener {

    StateHolder mState;
    private AccountRequester mAccountRequester;
    protected Typeface tfRegular;
    private ActivityRainChartBinding mBinding;

    protected Typeface tfLight;
    private boolean isLandscape = false;

    private SimpleDataBindingPositionAdapter<WaterDetailInfoBean.WaterRecordsListBean, ItemRainTimeDetailBinding> mAdapter;

    @Override
    protected void initViewModel() {

        mState = getActivityScopeViewModel(StateHolder.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        mAdapter = new SimpleDataBindingPositionAdapter<WaterDetailInfoBean.WaterRecordsListBean, ItemRainTimeDetailBinding>(this, R.layout.item_rain_time_detail, new DiffUtil.ItemCallback<WaterDetailInfoBean.WaterRecordsListBean>() {
            @Override
            public boolean areItemsTheSame(@NonNull WaterDetailInfoBean.WaterRecordsListBean oldItem, @NonNull WaterDetailInfoBean.WaterRecordsListBean newItem) {
                return false;
            }

            @Override
            public boolean areContentsTheSame(@NonNull WaterDetailInfoBean.WaterRecordsListBean oldItem, @NonNull WaterDetailInfoBean.WaterRecordsListBean newItem) {
                return false;
            }
        }) {
            @Override
            protected void onBindItem(ItemRainTimeDetailBinding binding, WaterDetailInfoBean.WaterRecordsListBean item, ViewHolder holder, int position) {
                binding.setVm(item);
            }
        };
        return new DataBindingConfig(R.layout.activity_rain_chart, BR.vm, mState)
                .addBindingParam(BR.adapter, mAdapter)
                .addBindingParam(BR.click, new ClickProxy());
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getLifecycle().addObserver(mAccountRequester);

        mState.titleBar.set(getIntent().getStringExtra("title"));
        mBinding = (ActivityRainChartBinding) getBinding();
        tfRegular = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf");

        tfLight = Typeface.createFromAsset(getAssets(), "OpenSans-Light.ttf");

        // 设置横屏切换按钮
        if (mBinding.titlebar != null && mBinding.titlebar.titleBarClear != null) {
            mBinding.titlebar.titleBarClear.setVisibility(View.VISIBLE);
            mBinding.titlebar.titleBarClear.setImageResource(R.drawable.ic_nsgf_video_big);
            mBinding.titlebar.titleBarClear.setOnClickListener(view -> {
                if (isLandscape) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                } else {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                }
                isLandscape = !isLandscape;
            });
        }

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + 1);
        mState.endDate.set(ymd.format(calendar.getTime()));
        mState.endDateSrc.set(ymd.format(calendar.getTime()) + "\n08:00");
        endTime = calendar;

        Calendar calendarStar = Calendar.getInstance();
        mState.startDate.set(ymd.format(calendarStar.getTime()));
        mState.startDateSrc.set(ymd.format(calendarStar.getTime()) + "\n08:00");
        starTime = calendarStar;


        mBinding.recyclerView.setNestedScrollingEnabled(false);

        mBinding.chart1.setNoDataText("暂无数据");
        UnitTo.setBorder(this, R.color.radio_text_check_color, R.color.radio_text_check_color, R.color.white, mBinding.ivNsgfWorkPMonth, 5);
        UnitTo.setBorder(this, R.color.color_1D2129, R.color.white, R.color.color_1D2129, mBinding.ivNsgfWorkNMonth, 5);
        getDatas();
        mAccountRequester.getWaterRecords().observe(this, new Observer<ResponseStatus<WaterDetailInfoBean>>() {
            @Override
            public void onChanged(ResponseStatus<WaterDetailInfoBean> WaterDetailInfoBeanResponseStatus) {
                getController().dismissLoading();
                if (WaterDetailInfoBeanResponseStatus.getResponseCode() == 200) {

                    mState.waterRecordsDetails.set(WaterDetailInfoBeanResponseStatus.getData());

                    if (null == mState.waterRecordsDetails.get().getRainRecordsList()) {
                        mState.waterRecordsDetails.get().setRainRecordsList(new ArrayList<>());
                    }

                    if (mState.waterRecordsDetails.get().getRainRecordsList().size() == 0) {
                        mBinding.notdata.setVisibility(View.VISIBLE);
                    } else {
                        mBinding.notdata.setVisibility(View.GONE);
                    }

                    initBarChart(WaterDetailInfoBeanResponseStatus.getData().getRainRecordsList());
                    setData(WaterDetailInfoBeanResponseStatus.getData().getRainRecordsList());
                } else {
                    showToast(WaterDetailInfoBeanResponseStatus.getMsg());
                }
            }
        });


        mAccountRequester.getHomeDeviceOpeningResult().observe(this, new Observer<ResponseStatus<List<HomeDeviceOpeningBean>>>() {
            @Override
            public void onChanged(ResponseStatus<List<HomeDeviceOpeningBean>> listResponseStatus) {
                if (listResponseStatus.getResponseCode() == 200) {
                    ArrayAdapter<HomeDeviceOpeningBean> adapter = new ArrayAdapter<>(RainDetailActivity.this,
                            android.R.layout.simple_spinner_item, listResponseStatus.getData());
                    mBinding.actionBarSpinner.setAdapter(adapter);
                    if (!listResponseStatus.getData().isEmpty()) {
                        facilityCode = listResponseStatus.getData().get(0).getFacilityCode();
                        datas = listResponseStatus.getData();
                        getRainDetail();
                    }
                }
            }
        });
        mBinding.actionBarSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                facilityCode = datas.get(position).getFacilityCode();
                getRainDetail();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // 未选择任何项时的处理
            }
        });
        initBarChart(null);
    }

    List<HomeDeviceOpeningBean> datas = new ArrayList<>();

    private void getRainDetail() {

        mAccountRequester.getMonitorRainDetails(UserInfo.getInstance().getProjectCode(),
                facilityCode,
                mState.startDate.get() + " 08:00:00",
                mState.endDate.get() + " 08:00:00");
    }

    private String facilityCode = "";

    YAxis leftAxis;

    /**
     * 初始化BarChart图表
     */
    private void initBarChart(List<WaterDetailInfoBean.WaterRecordsListBean> list) {


        mBinding.chart1.setOnChartValueSelectedListener(this);

        mBinding.chart1.setDrawBarShadow(false);
        mBinding.chart1.setDrawValueAboveBar(true);

        mBinding.chart1.getDescription().setEnabled(false);

        // if more than 60 entries are displayed in the chart, no values will be
        // drawn
        mBinding.chart1.setMaxVisibleValueCount(60);

        // draw points over time
        mBinding.chart1.animateX(1500);
        mBinding.chart1.animateY(1500);
        // scaling can now only be done on x- and y-axis separately
        mBinding.chart1.setPinchZoom(false);

        mBinding.chart1.setDrawGridBackground(false);
        // chart.setDrawYLabels(false);

        XAxis xAxis = mBinding.chart1.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setTypeface(tfLight);
        xAxis.setDrawGridLines(false);
//        xAxis.setGranularity(1f); // only intervals of 1 day

        // 根据数据数量动态设置标签数量，小于8用实际数量，大于等于8设置8
        int labelCount = 8;
        if (list != null && list.size() > 0) {
            labelCount = list.size() < 8 ? list.size() : 8;
        }
        xAxis.setLabelCount(Math.max(labelCount, 1), true); // 至少显示1个标签
        xAxis.setLabelRotationAngle(-30f);


        leftAxis = mBinding.chart1.getAxisLeft();
        leftAxis.setTypeface(tfLight);
        leftAxis.setLabelCount(Math.max(labelCount, 1), true);
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        leftAxis.setSpaceTop(15f);
        leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
        // vertical grid lines
        leftAxis.enableGridDashedLine(10f, 10f, 0f);
        mBinding.chart1.getAxisRight().setEnabled(false);
        
        // 根据横竖屏状态设置不同的偏移量
        boolean isLandscapeMode = getResources().getConfiguration().orientation == android.content.res.Configuration.ORIENTATION_LANDSCAPE;
        if (isLandscapeMode) {
            // 横屏时增加偏移量，确保XY轴标签完全显示
            mBinding.chart1.setExtraBottomOffset(40f); // X轴标签旋转后需要更多空间
            mBinding.chart1.setExtraLeftOffset(30f); // Y轴标签需要更多空间
            mBinding.chart1.setExtraRightOffset(10f); // 右侧也需要一些空间
        } else {
            // 竖屏时的偏移量
            mBinding.chart1.setExtraBottomOffset(10f);
            mBinding.chart1.setExtraLeftOffset(10f);
            mBinding.chart1.setExtraRightOffset(0f);
        }


        xAxis.setValueFormatter(new ValueFormatter() {
            // 添加24小时制时间格式化器
            private SimpleDateFormat time24hFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());

            @Override
            public String getAxisLabel(float value, AxisBase axis) {
                if (mState.waterRecordsDetails.get() == null ||
                        mState.waterRecordsDetails.get().getRainRecordsList() == null ||
                        mState.waterRecordsDetails.get().getRainRecordsList().size() == 0) {
                    return "";
                }

                int index = (int) value;
                if (index < 0 || index >= mState.waterRecordsDetails.get().getRainRecordsList().size()) {
                    return "";
                }

                String tradeDate = mState.waterRecordsDetails.get().getRainRecordsList().get(index).getTm();
                // 直接使用24小时制格式化时间，避免12小时制导致的问题
                try {
                    // 假设原始时间格式为"yyyy-MM-dd HH:mm:ss"
                    SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
                    Date date = originalFormat.parse(tradeDate);
                    return time24hFormat.format(date);
                } catch (Exception e) {
                    // 如果解析失败，使用原有Utils.formatTime方法作为备选
                    return Utils.formatTime(tradeDate);
                }
            }
        });

        MyMarkerView mv = new MyMarkerView(this, xAxis.getValueFormatter(), leftAxis.getValueFormatter(), "雨量", "#3CC3DB", list);
        mv.setChartView(mBinding.chart1);
        mBinding.chart1.setMarker(mv);
        mBinding.chart1.invalidate();

        Legend l = mBinding.chart1.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);
        l.setForm(Legend.LegendForm.SQUARE);
        l.setFormSize(9f);
        l.setTextSize(11f);
        l.setXEntrySpace(4f);
        l.setEnabled(false);

        while (!mBinding.chart1.isFullyZoomedOut()) {
            mBinding.chart1.zoomOut();
        }
    }

    private void setData(List<WaterDetailInfoBean.WaterRecordsListBean> list) {

        if (null == list)
            return;

        ArrayList<BarEntry> values = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            float val = (float) list.get(i).getDrp();
            values.add(new BarEntry(i, val));
        }

        // 处理只有一条数据时，y轴不显示刻度的问题
        if (values.size() == 1) {
            float singleValue = values.get(0).getY();
            // 如果值为0，设置一个默认范围
            if (singleValue == 0) {
                leftAxis.setAxisMaximum(10f);
            } else {
                // 如果值不为0，设置一个合适的最大值（比原值高一些）
                leftAxis.setAxisMaximum(singleValue * 1.5f);
            }
        } else if (values.size() > 0) {
            // 检查是否所有值都相同
            boolean allSame = true;
            float firstValue = values.get(0).getY();
            for (BarEntry entry : values) {
                if (entry.getY() != firstValue) {
                    allSame = false;
                    break;
                }
            }
            if (allSame && firstValue == 0) {
                leftAxis.setAxisMaximum(10f);
            } else if (allSame) {
                leftAxis.setAxisMaximum(firstValue * 1.5f);
            } else {
                // 正常情况，让图表自动调整
                leftAxis.resetAxisMaximum();
            }
        }

        BarDataSet set1;

        if (mBinding.chart1.getData() != null &&
                mBinding.chart1.getData().getDataSetCount() > 0) {
            set1 = (BarDataSet) mBinding.chart1.getData().getDataSetByIndex(0);
            set1.setValues(values);
            mBinding.chart1.getData().notifyDataChanged();
            mBinding.chart1.notifyDataSetChanged();

        } else {
            set1 = new BarDataSet(values, "");

            List<GradientColor> gradientFills = new ArrayList<>();
            gradientFills.add(new GradientColor(Color.parseColor("#1F8FFC"), Color.parseColor("#3CC3DB")));
            set1.setGradientColors(gradientFills);
            set1.setColor(Color.parseColor("#ffffff"));


            ArrayList<IBarDataSet> dataSets = new ArrayList<>();
            dataSets.add(set1);

            BarData data = new BarData(dataSets);
            data.setValueTextSize(10f);
            data.setValueTypeface(tfLight);
            if (set1.getValues().size() < 4)
                data.setBarWidth(0.1f);
            else
                data.setBarWidth(0.9f);
            data.setDrawValues(false);

            mBinding.chart1.setData(data);
        }
        mBinding.chart1.invalidate();
    }

    private void getDatas() {
        mAccountRequester.conservancyHydrologyList(UserInfo.getInstance().getProjectCode(), "hydrology.station.type.3");

    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {
        Log.i("Entry selected", e.toString());
        Log.i("LOW HIGH", "low: " + mBinding.chart1.getLowestVisibleX() + ", high: " + mBinding.chart1.getHighestVisibleX());
        Log.i("MIN MAX", "xMin: " + mBinding.chart1.getXChartMin() + ", xMax: " + mBinding.chart1.getXChartMax() + ", yMin: " + mBinding.chart1.getYChartMin() + ", yMax: " + mBinding.chart1.getYChartMax());
    }

    @Override
    public void onNothingSelected() {
        Log.i("Nothing selected", "Nothing selected.");
    }

    @Override
    public void onBackPressed() {
        int orientation = getRequestedOrientation();
        if (orientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            // Activity 设置为横屏，先切换回竖屏
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            isLandscape = false;
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onClickSecurity(View v) {
        super.onClickSecurity(v);
        if (v.getId() == R.id.title_bar_back) {
            int orientation = getRequestedOrientation();
            if (orientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                // Activity 设置为横屏，先切换回竖屏
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                isLandscape = false;
            } else {
                finish();
            }
        }
    }

    @Override
    public void onConfigurationChanged(android.content.res.Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // 更新横屏状态
        isLandscape = (newConfig.orientation == android.content.res.Configuration.ORIENTATION_LANDSCAPE);
        // 横竖屏切换时，重新初始化图表以确保正确显示
        if (mBinding != null && mBinding.chart1 != null && mState.waterRecordsDetails.get() != null) {
            // 延迟一下，确保布局已经完成
            mBinding.chart1.post(() -> {
                List<WaterDetailInfoBean.WaterRecordsListBean> list = 
                    mState.waterRecordsDetails.get().getRainRecordsList();
                if (list != null) {
                    initBarChart(list);
                    setData(list);
                }
            });
        }
    }

    private Calendar starTime, endTime;

    private static SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());


    public class ClickProxy {

        public void pMonth() {

            starTime.set(Calendar.DAY_OF_MONTH, starTime.get(Calendar.DAY_OF_MONTH) - 1);
            mState.startDate.set(Kits.Date.getYmd(starTime.getTimeInMillis()));
            mState.startDateSrc.set(Kits.Date.getYmd(starTime.getTimeInMillis()) + "\n08:00");


            endTime.setTime(starTime.getTime());
            endTime.set(Calendar.DAY_OF_MONTH, endTime.get(Calendar.DAY_OF_MONTH) + 1);
            mState.endDate.set(Kits.Date.getYmd(endTime.getTimeInMillis()));
            mState.endDateSrc.set(Kits.Date.getYmd(endTime.getTimeInMillis()) + "\n08:00");

            getController().displayLoading();
            getDatas();

        }

        public void nMonth() {


            endTime.set(Calendar.DAY_OF_MONTH, endTime.get(Calendar.DAY_OF_MONTH) + 1);
            mState.endDate.set(Kits.Date.getYmd(endTime.getTimeInMillis()));
            mState.endDateSrc.set(Kits.Date.getYmd(endTime.getTimeInMillis()) + "\n08:00");

            starTime.setTime(endTime.getTime());
            starTime.set(Calendar.DAY_OF_MONTH, starTime.get(Calendar.DAY_OF_MONTH) - 1);
            mState.startDate.set(Kits.Date.getYmd(starTime.getTimeInMillis()));
            mState.startDateSrc.set(Kits.Date.getYmd(starTime.getTimeInMillis()) + "\n08:00");


            getController().displayLoading();
            getDatas();
        }


        public void screenStarTime() {

            boolean[] type = new boolean[]{true, true, true, false, false, false};//显示类型 默认全部显示

            TimePickerView mTimePickerView = new TimePickerView.Builder(RainDetailActivity.this, new TimePickerView.OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    mState.startDate.set(ymd.format(date));
                    mState.startDateSrc.set(ymd.format(date) + "\n08:00");

                    getDatas();
                    starTime.setTime(date);
                }
            }).isCyclic(false)
                    .setRangDate(null, null)
                    .setType(type)
                    .setTitleText("开始日期")
                    .setDate(starTime).build();

            mTimePickerView.show();


        }

        public void screenEndTime() {

            boolean[] type = new boolean[]{true, true, true, false, false, false};//显示类型 默认全部显示

            TimePickerView mTimePickerView = new TimePickerView.Builder(RainDetailActivity.this, new TimePickerView.OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    mState.endDate.set(ymd.format(date));
                    mState.endDateSrc.set(ymd.format(date) + "\n08:00");
                    getDatas();
                    endTime.setTime(date);
                }
            }).isCyclic(false)
                    .setRangDate(null, null)
                    .setType(type)
                    .setTitleText("结束日期")
                    .setDate(endTime).build();

            mTimePickerView.show();


        }

    }
}
